<?php

// Namespace

namespace Snsfg;


// Dependencies

require_once(PATH_APPLICATION . 'Class/ISocialNetworkDriver.php');
require_once(PATH_APPLICATION . 'Component/Weibo/lib/saetv2.ex.class.php');

require_once(PATH_APPLICATION . 'Model/CAccount.php');
require_once(PATH_APPLICATION . 'Model/CPostStatus.php');


/**
 * CWeiboDriver allows to run and use the social network driver for PHP
 * This class is the implementation of the interface ISocialNetworkDriver
 *
 * @package		Gt_Sync
 * @category	Driver
 */

class CWeiboDriver implements ISocialNetworkDriver
{

	/**
	 *
	 */

	public function completeConnection(&$account)
	{
		$code = fv('code', true);

		$callBack = array();
		$result = array();
		$callBack['code'] = fv('code');
		$callBack['redirect_uri'] = url('api/json/Account.completeConnection');
		try 
		{

			$saeTOAuthV2 = new \SaeTOAuthV2
			(
				pref('[Snsfg]/socialNetwork/weibo/appid'),
				pref('[Snsfg]/socialNetwork/weibo/apikey')
			);

			$oauthInfo = $saeTOAuthV2->getAccessToken('code', $callBack);
			
		}

		catch (OAuthException $e) {

		}

		$dataToEf['access_token'] = $oauthInfo['access_token'];
		$dataToEf['uid'] = $oauthInfo['uid'];

		// Get and store the personal information

		$saeTClientV2 = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $oauthInfo['access_token']
									)
								);

		$userInfo = $saeTClientV2->show_user_by_id($oauthInfo['uid']);

		// Try to get the social network account

		$account->loadAccount('internalId', $userInfo['id'], SOCIAL_NETWORK_WEIBO);
		
		$account->setPrivateApiToken($oauthInfo['access_token']);
		$account->setInternalId($userInfo['id']);
		$account->setScreenName($userInfo['screen_name']);
		$account->setAvatar($userInfo['profile_image_url']);
		$account->setStatusesCount($userInfo['statuses_count']);
		$account->setFollowersCount($userInfo['followers_count']);
		$account->setFriendsCount($userInfo['friends_count']);
		$account->setTimeOfExpirationOfApiToken($oauthInfo['remind_in'] + time());

		return $dataToEf;
	}


	/**
	 *
	 */

	public function connectDriver($params = null)
	{
		$saeTClientV2 = new \SaeTClientV2
		(
			pref('[Snsfg]/socialNetwork/weibo/appid'),
			pref('[Snsfg]/socialNetwork/weibo/apikey'),
			$params['privateApiToken']
		);

		return $saeTClientV2;
	}


	/**
	 *
	 */

	public function disconnect(&$account)
	{
		$saeTClientV2 = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$result = $saeTOAuthV2->disconnect();

		return $result;
	}



	public function getGroups(&$account)
	{
		
	}

	/**
	 *
	 */

	public function postStatus(&$account, $messageData)
	{
		$saeTClientV2 = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);
		
		$dataToEf = array();
		$postStatus = new CPostStatus();

		if('image' == $messageData['type']) 
		{
			$result = $saeTClientV2->upload($messageData['content'], $messageData['pic']);

			$postStatus->setPicture($messageData['pic']);

			$dataToEf['picture'] = $messageData['pic'];
			
			/*
			$result = $saeTClientV2->upload($messageData['content'], $messageData['pic']['tmp_name']);

			if(is_uploaded_file($messageData['pic']['tmp_name']))
			{
				//$pathToUploadFile = PATH_TEMPORARY . $account->getInternalId() . $account->getReference() . md5($messageData['pic']['tmp_name']) . $messageData['pic']['name'];
				$picSaveName = $account->getInternalId() . $account->getReference() . md5($messageData['pic']['tmp_name']) . $messageData['pic']['name'];
				$result = copy( $messageData['pic']['tmp_name'], PATH_TEMPORARY . $picSaveName );

				$postStatus->setPicture($picSaveName);
			}
			*/
			/*
			echo '##########';
			$rr['md'] = $messageData;
			$rr['rst'] = $result;
			
			var_dump($rr);
			echo '##########';
			exit;
			*/
		}
		else
		{

			$result = $saeTClientV2->update($messageData['content']);
		}

		if($messageData['link'] != '')
		{
			$postStatus->setLink($messageData['link']);
		}

		$preg = '/http:\/\/t.cn\/[a-zA-Z0-9]*/';

		if(preg_match_all($preg, $result['text'],$shortLinkRaws)) {
			$shortLinkStr = implode(',', $shortLinkRaws[0]);
			$postStatus->setShortUrl($shortLinkStr);
			$dataToEf['link'] = $shortLinkStr;
		}

		$postStatus->setAccountId($result['user']['id']);
		$postStatus->setContent($result['text']);
		$postStatus->setInternalId(number_format($result['id'], 0, '', ''));
		$postStatus->setRepostsCount(0);
		$postStatus->setCommentsCount(0);
		$postStatus->setSource($result['source']);
		$postStatus->setCreatedAt(strtotime($result['created_at']));
		$postStatus->setSocialNetwork($account->getSocialNetwork());
		$postStatus->setType($messageData['type']);
		$postStatus->save();

		$dataToEf['statusId'] = number_format($result['id'], 0, '', '');
		$dataToEf['content'] = $result['text'];
		$dataToEf['socialNetwork'] = $account->getSocialNetwork();
		$dataToEf['efId'] = $account->getEfId();

		return $dataToEf;
	}


	/**
	 *
	 */
	 	
	public function startConnection(&$account)
	{

		$saeTOAuthV2 = new \SaeTOAuthV2
		(
			pref('[Snsfg]/socialNetwork/weibo/appid'),
			pref('[Snsfg]/socialNetwork/weibo/apikey')
		);

		v('SESSION::accountId', $account->getId());
		v('SESSION::accountReference', $account->getReference());

		$authorizeUrl = $saeTOAuthV2->getAuthorizeURL
		(
			url('api/json/Account.completeConnection'),
			'code'
		);
		
		return $authorizeUrl;
	}


	/**
	 *
	 */

	public function updateStatus(&$account) {

 		$rawStatuses = $account->getStatuses();

		$saeTClientV2 = $this->connectDriver
						(
							array
							(
								'privateApiToken' => $account->getPrivateApiToken()
							)
						);
		
		$dataToEf = array();
		$status = new CPostStatus();

		foreach ($rawStatuses as $rawStatus) {
			$newStatusRow = array();

			$status->reset();
			$status->loadSecure($rawStatus['id'], $rawStatus['reference']);

			$newStatusRow = $saeTClientV2->show_status($rawStatus['internalId']);
			if (isset($newStatusRow['error'])) {
				if($newStatusRow['error_code'] == 20101){
					$status->delete();
					$status->save();
				}
			}else{

				$status->setRepostsCount($newStatusRow['reposts_count']);
				$status->setCommentsCount($newStatusRow['comments_count']);
				$status->save();

				$dataToEf[$rawStatus['internalId']]['repostCount'] = $newStatusRow['reposts_count'];
				$dataToEf[$rawStatus['internalId']]['commentCount'] = $newStatusRow['comments_count'];
			}
		}

		return $dataToEf;
	}

}

?>
